package com.play.ballen.me.vm

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.hyphenate.easeui.domain.EaseUser
import com.hyphenate.easeui.manager.EaseThreadManager
import com.mw.plp.uim.JIm
import com.mw.plp.uim.common.interfaceOrImplement.ResultCallBack
import com.play.ballen.config.KVConst
import com.play.ballen.data.LoginResult
import com.play.ballen.data.UserBean
import com.play.ballen.network.ApiRepository
import com.play.ballen.network.BallenRxHelper
import com.play.ballen.utils.UserInfoManager
import com.yuven.appframework.network.RxSchedulerHelper
import com.yuven.appframework.util.MMKVUtil
import com.yuven.appframework.util.MMKVUtil.decodeString
import com.yuven.appframework.util.addToDisposable
import com.yuven.baselib.component.viewmodel.BaseViewModel
import com.yuven.baselib.utils.Logger

open class BaseUserViewModel : BaseViewModel() {
    val model = ApiRepository()

    val tokenStatus = MutableLiveData<Int>()//查询用户基本信息
    val imLoginStatus = MutableLiveData<Int>()//查询用户基本信息


    fun getUserInfo(loginResult: LoginResult){
        UserInfoManager.setToken(loginResult.JiyuToken)
        model.getUserInfo()
            .onErrorResumeNext(BallenRxHelper.HttpErrorHandleFunc())
            .compose(BallenRxHelper.transformResponse())
            .compose(RxSchedulerHelper.io_main())
            .subscribe({
                loginIm(loginResult,it);
            }, {
                UserInfoManager.setToken("")
                tokenStatus.value=1
                imLoginStatus.value=-1
                toastLiveData.value = "登录失败，用户信息获取失败"
            }).addToDisposable(compositeDisposable)
    }

    //放到登录页面调用了，不然报错
    fun loginIm(loginResult: LoginResult, user: UserBean){
        UserInfoManager.setUserInfo(user)
        MMKVUtil.encode(KVConst.PHOTO, user.info.avatar_url,false)
        MMKVUtil.encode(KVConst.NICK_NAME, user.info.nickname,false)
        JIm.loginIm(user.hx_user_name,loginResult.HXToken, object : ResultCallBack<LiveData<EaseUser?>?>() {
            override fun onSuccess(value: LiveData<EaseUser?>?) {
                Logger.i("IM登录 成功--")
                EaseThreadManager.getInstance().runOnMainThread({
                    imLoginStatus.value=1;
                    UserInfoManager.setLoginSuccess()
                })
            }
            override fun onError(error: Int, errorMsg: String) {
                Logger.i("IM登录 Fail-- $error/$errorMsg")
//                UserInfoManager.logout()
                EaseThreadManager.getInstance().runOnMainThread({
                    UserInfoManager.setToken("")
                    tokenStatus.value=1
                    imLoginStatus.value=-1
                    toastLiveData.value = "登录失败，请稍后重试"
                })
            }
        })
    }


}